package com.strongbj.iot.devices.guis.request.handle;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.strongbj.core.message.IMessageHandle;
import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.common.NetMapping;
import com.strongbj.iot.devices.dam.request.entity.ScreenCommandEntity;
import com.strongbj.iot.devices.guis.message.GUISOSMessageFactory;
import com.strongbj.iot.devices.guis.message.MQMessageOfGUIS;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 屏幕透传
 * @author yuzhantao
 *
 */
public class TransmissionHandle implements IMessageHandle<MQMessageOfGUIS, Object> {
	private static final Logger logger = LogManager.getLogger(TransmissionHandle.class);
	private static final GUISOSMessageFactory guisMessageFactory = new GUISOSMessageFactory();
	private static final String ACTION_CODE = "screenCommand";

	@Override
	public boolean isHandle(MQMessageOfGUIS t) {
		if (t.getActioncode().equals(ACTION_CODE)) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, MQMessageOfGUIS t) {
		logger.info("从系统收到控制硬件小屏的透传数据 recive screen");
		Object obj = t.getAwsPostdata();
		ScreenCommandEntity scObj = null;
		if (obj instanceof JSONObject ) {
			scObj = JSON.toJavaObject((JSONObject) obj, ScreenCommandEntity.class);
		}else if( obj instanceof String){
			scObj = JSON.toJavaObject((JSONObject) JSON.parseObject(obj+""), ScreenCommandEntity.class);
		} else {
			scObj = (ScreenCommandEntity) obj;
		}

		final ScreenCommandEntity sc = scObj;
		Channel tmpChannel = null;
		if (ctx == null) {
			tmpChannel = NetMapping.getInstance().getChannel(sc.getRackConverCode());
		} else {
			tmpChannel = ctx.channel();
		}
		final Channel channel = tmpChannel;
		ITaskManager taskManager = DAMManager.getTaskManager(sc.getRackConverCode());
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				sendDatasToDAM(channel, sc.getRackConverCode(), ByteUtil.hexStringToBytes(sc.getCommand()));
			}
		});

		return null;
	}

	private void sendDatasToDAM(Channel channel, String devCode, byte[] datas) {
		if (channel != null && channel.isActive()) {
			// 将命令发送到屏幕硬件

			final byte[] retDatas = guisMessageFactory.createGUISOSMessage(ByteUtil.hexStringToBytes(devCode),
					(byte) 0x31, datas);
			logger.info("预下发透传命令到屏幕 编号:{} 命令={}  ", devCode, ByteUtil.byteArrToHexString(retDatas));
			ByteBuf bs = Unpooled.copiedBuffer(retDatas);
			ChannelFuture cf = channel.writeAndFlush(bs);

			cf.addListener(new ChannelFutureListener() {

				@Override
				public void operationComplete(ChannelFuture future) throws Exception {
					if (future.isSuccess()) {
						logger.info("下发透传命令到屏幕成功 编号:{} 命令={}  ", devCode, ByteUtil.byteArrToHexString(datas, true));
					} else {
						logger.error("下发透传命令到屏幕失败 编号:{} 命令={}  ", devCode, ByteUtil.byteArrToHexString(datas, true));
					}
				}

			});
		} else {
			logger.error("{} 主机没有找到指定channel", devCode);
		}
	}

}
